package com.xt.base.util;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * 编码密码工具
 * 
 * <p>
 * <a h ref="StringUtil.java.html"><i>View Source</i></a>
 * </p>
 * 
 * Copyright: Copyright (c) 2005 <br>
 * 
 * @author 杨洪波
 * @version $Revision: 225 $<br>
 *          $Id: StringUtil.java 225 2005-12-08 09:46:59Z yangkaifeng $
 */
public class StringUtil {
	// ~ Static fields/initializers
	// =============================================

	private final static Logger log = Logger.getLogger(StringUtil.class);

	// ~ Methods
	// ================================================================

	/**
	 * Encode a string using algorithm specified in web.xml and return the
	 * resulting encrypted password. If exception, the plain credentials string
	 * is returned
	 * 
	 * @param password
	 *            Password or other credentials to use in authenticating this
	 *            username
	 * @param algorithm
	 *            Algorithm used to do the digest
	 * 
	 * @return encypted password based on the algorithm.
	 */
	public static String encodePassword(String password, String algorithm) {
		byte[] unencodedPassword = password.getBytes();

		MessageDigest md = null;

		try {
			// first create an instance, given the provider
			md = MessageDigest.getInstance(algorithm);
		} catch (Exception e) {
			log.error("Exception: " + e);

			return password;
		}

		md.reset();

		// call the update method one or more times
		// (useful when you don't know the size of your data, eg. stream)
		md.update(unencodedPassword);

		// now calculate the hash
		byte[] encodedPassword = md.digest();

		StringBuffer buf = new StringBuffer();

		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 0x10) {
				buf.append("0");
			}

			buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}

		return buf.toString();
	}

	/**
	 * Encode a string using Base64 encoding. Used when storing passwords as
	 * cookies.
	 * 
	 * This is weak encoding in that anyone can use the decodeString routine to
	 * reverse the encoding.
	 * 
	 * @param str
	 * @return String
	 */
	public static String encodeString(String str) {
		sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
		return encoder.encodeBuffer(str.getBytes()).trim();
	}

	/**
	 * Decode a string using Base64 encoding.
	 * 
	 * @param str
	 * @return String
	 */
	public static String decodeString(String str) {
		sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
		try {
			return new String(dec.decodeBuffer(str));
		} catch (IOException io) {
			throw new RuntimeException(io.getMessage(), io.getCause());
		}
	}

	/**
	 * 给定字符串及需从右侧取得的长度,取字符串右边的子串
	 * 
	 * @param s
	 *            字符串,
	 * @param pos
	 *            需取得的长度
	 * @return 子串
	 */
	public static String right(String s, int pos) {
		// 反转字符串后取数据
		String dido = new StringBuffer(s).reverse().substring(0, pos);
		StringBuffer sb = new StringBuffer(dido).reverse();
		String didoleo = new String(sb);
		return didoleo;

	}

	/**
	 * 给定字符串及需从左侧取得的长度,从字符串左边的取子串
	 * 
	 * @param s
	 *            字符串,
	 * @param pos
	 *            需取得的长度
	 * @return 子串
	 */
	public static String left(String s, int pos) {
		// 反转字符串后取数据
		String dido = new StringBuffer(s).substring(0, pos);
		String didoleo = new String(dido);
		return didoleo;

	}

	/**
	 * 计算字符串的SHA数字摘要，以byte[]形式返回
	 */
	public static byte[] MdigestSHA(String source) {
		try {
			MessageDigest thisMD = MessageDigest.getInstance("SHA");
			byte[] digest = thisMD.digest(source.getBytes("UTF8"));
			return digest;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 计算byte[]的SHA数字摘要，以byte[]形式返回
	 */
	public static byte[] MdigestSHA(byte[] source) {
		try {
			MessageDigest thisMD = MessageDigest.getInstance("SHA");
			byte[] digest = thisMD.digest(source);
			return digest;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 计算字符串的MD5数字摘要，以byte[]形式返回
	 */
	public static byte[] MdigestMD5(String source) {
		try {
			MessageDigest thisMD = MessageDigest.getInstance("MD5");
			byte[] digest = thisMD.digest(source.getBytes("UTF8"));
			return digest;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 计算byte[]的数MD5字摘要，以byte[]形式返回
	 */
	public static byte[] MdigestMD5(byte[] source) {
		try {
			MessageDigest thisMD = MessageDigest.getInstance("MD5");
			byte[] digest = thisMD.digest(source);
			return digest;
		} catch (Exception e) {
			return null;
		}
	}

	public static String makePassword(String givepasswd) {
		if (StringUtils.isEmpty(givepasswd))
			return "";
		return givepasswd;
		/*byte[] t1 = MdigestMD5(givepasswd);
		String tempPassword = "";
		for (int i = 0; i < t1.length; i++) {
			tempPassword += Integer.toString(Math.abs(t1[i]));
		}
		return tempPassword;*/
	}

	/**
	 * 
	 * 将字符串List使用指定的分隔符合并成一个字符串。
	 * 
	 * @param list
	 *            List
	 * 
	 * @param delim
	 *            String
	 * 
	 * @return String
	 * 
	 */

	@SuppressWarnings("unchecked")
	public static String combineList(List list, String delim) {
		if (list == null || list.size() == 0) {
			return "";
		} else {
			StringBuffer result = new StringBuffer();
			for (int i = 0; i < list.size() - 1; i++) {
				result.append(list.get(i));
				result.append(delim);
			}
			result.append(list.get(list.size() - 1));
			return result.toString();
		}
	}
	
	public static void main(String[] args){
		System.out.println(StringUtil.makePassword("1"));
	}

}
